import { defineStore } from "pinia";
import { store } from "@/store";
import { useTagsViewStore, TagView } from "@/store/modules/tagsView";
import { useUserStore } from "@/store/modules/user";
import { getTeachCourseInfo } from "@/api/course";
import { Courseinfo } from "@/api/course/types";

export const useCourseStore = defineStore("course", () => {
  // state 变量
  // 课程ID
  const courseId = ref();
  // 任务ID
  const experimentId = ref();
  // 课程名称
  const courseName = ref("");
  // 助教
  const nickname = ref("");
  // 主教
  const leaderName = ref("");
  // 课程图片
  const wallpaperUrl = ref("");
  // 头像
  const avatar = ref("");
  // 用户角色编码集合 → 判断路由权限
  const roles = ref<Array<string>>([]);
  // 用户权限编码集合 → 判断按钮权限
  const perms = ref<Array<string>>([]);
  // 导航栏
  const tagsViewStore = useTagsViewStore();
  // 用户信息
  const userStore = useUserStore();

  // actions
  // 登陆学习课程信息
  function teachCourse(id: number) {
    return new Promise<void>((resolve, reject) => {
      courseId.value = id;
      resolve();
    });
  }
  // 登陆学习课程信息
  function editSaveExp(id: number) {
    return new Promise<void>((resolve, reject) => {
      experimentId.value = id;
      resolve();
    });
  }
  // 获取课程信息
  function getCourseInfo(id: number) {
    return new Promise<Courseinfo>((resolve, reject) => {
      getTeachCourseInfo(id)
        .then(({ data }) => {
          if (!data) {
            return reject("Verification failed, please Login again.");
          }
          courseId.value = id;
          courseName.value = data.name!;
          wallpaperUrl.value = data.wallpaperUrl!;
          nickname.value = data.nickname!;
          leaderName.value = data.leaderName!;
          avatar.value = data.avatar!;
          roles.value = data.roles!;
          perms.value = data.perms!;

          userStore.addCourseModel(data);
          resolve(data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  // 重置课程信息
  function resetCourse() {
    courseId.value = null;
    courseName.value = "";
    wallpaperUrl.value = "";
    nickname.value = "";
    roles.value = [];
    perms.value = [];
  }

  // 重置课程信息
  function resetExp() {
    experimentId.value = null;
  }

  // 重置课程信息
  function removeCache() {
    return new Promise<void>((resolve, reject) => {
      const views = tagsViewStore.visitedViews.filter((view: TagView) => {
        return view.meta?.layout === "CourseLayout";
      });
      tagsViewStore
        .delViews(views)
        .then(() => {
          resolve();
        })
        .catch(() => {
          reject();
        });
    });
  }

  return {
    courseId,
    courseName,
    wallpaperUrl,
    nickname,
    roles,
    perms,
    avatar,
    leaderName,
    experimentId,
    getCourseInfo,
    resetCourse,
    removeCache,
    teachCourse,
    editSaveExp,
    resetExp,
  };
});

// 非setup
export function useCourseStoreHook() {
  return useCourseStore(store);
}
